package study.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;

@Configuration
public class GatewaySentinelConfigurationDemo {

    @PostConstruct
    public void doInit(){
        initGatewayRules();
        initCustomizedApis();
    }

    /**
     * 初始化限流规则
     */
    private void initGatewayRules(){
        Set<GatewayFlowRule> rules=new HashSet<>();
        GatewayFlowRule gatewayFlowRule=new GatewayFlowRule("core2")
                .setCount(1)
                .setIntervalSec(1);
        //resourceMode：资源模型，
        // 限流规则是针对API Gateway的route（RESOURCE_MODE_ROUTE_ID）
        // 还是用户在Sentinel中定义的API分组（RESOURCE_MODE_CUSTOM_API_NAME），默认是route
        GatewayFlowRule customerFlowRule=new GatewayFlowRule("first_customized_api").
                setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
                .setCount(2)
                .setIntervalSec(1);
        rules.add(gatewayFlowRule);
        rules.add(customerFlowRule);
        GatewayRuleManager.loadRules(rules);
    }
    /**
     *自定义API分组限流案例：让多个Route共用一个限流规则。
     * ***/
    private void initCustomizedApis(){
        Set<ApiDefinition> definitions=new HashSet<>();
        ApiDefinition apiDefinition=new ApiDefinition("first_customized_api");
        apiDefinition.setPredicateItems(new HashSet<ApiPredicateItem>(){{
            add(new ApiPathPredicateItem().setPattern("/foo/**"));
            add(new ApiPathPredicateItem().setPattern("/baz/**").setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
        }});
        definitions.add(apiDefinition);
        GatewayApiDefinitionManager.loadApiDefinitions(definitions);
    }
}
